package com.framework.module_google

import android.app.Activity
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry
import org.json.JSONArray
import org.json.JSONObject
import java.io.File

/**
 *  flutterPlugin: 获取到插件的基础渲染引擎，AppContext等等
 *  ActivityAware: 可以获取到与Activity有关的
 *  MethodCallHandler：双方的通道调用
 *
 *  特别注意点：
 */
class LibCloudStoragePlugin : FlutterPlugin, MethodCallHandler , ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    var currentActivity:Activity?=null
    var activityPluginBinding:ActivityPluginBinding?=null
    var lifecycle:Lifecycle?=null
    private lateinit var context: Context //全局的application
    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "lib_cloud_storage")
        channel.setMethodCallHandler(this)
        context = flutterPluginBinding.applicationContext
    }

    private val method_upload_to_google_cloud = "uploadToGoogleCloud"//谷歌云盘存储

    private val method_google_login="google_login_sign"//谷歌登录
    private val method_google_download="google_drive_download"//谷歌云盘下载

    private val method_google_file_list="google_drive_file_list"//谷歌云盘中文件列表
    override fun onMethodCall(call: MethodCall, result: Result) {
        if (call.method == "getPlatformVersion") {
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else if (call.method == method_upload_to_google_cloud) {
              handleGoogleDriveUpload(call,result)
        } else if (call.method==method_google_login){
               handleGoogleSignLogin(call,result)
        }else if (call.method==method_google_download){
            handleGoogleDriveDownload(call,result)
        }else if (call.method==method_google_file_list){
             handleGoogleDriveFileList(call,result)
        }else {
            result.notImplemented()
        }
    }


    private fun  handleGoogleDriveFileList(call: MethodCall, result: Result){
        val json = JSONObject(call.arguments as String)
        val email = json.optString("email")
        val  prefix=json.optString("prefix")
        GoogleApi.initDriveByGoogleAccount(this.context, email)
        GoogleApi.queryFileList(prefix,object : GoogleApi.GoogleApiListener<JSONArray> {
            override fun success(data: JSONArray) {
                try {
                    //LogUtils.printI("download success $data")
                    val temp=JSONObject().apply {
                        this.put("code",0)
                        this.put("fileList",data)
                    }.toString()
                    result.success(temp)
                }catch (e:Exception){
                    e.printStackTrace()
                }
            }
            override fun error(e: Exception) {
                try {
                    LogUtils.printException("download fair ",e)
                    handleErrorResp(e.message,result)
                }catch (e:Exception){
                    e.printStackTrace()
                }

            }
        })
    }
    private fun  handleGoogleDriveDownload(call: MethodCall, result: Result){
        val json = JSONObject(call.arguments as String)
        val email = json.optString("email")
        val fileId = json.optString("fileId")
        GoogleApi.initDriveByGoogleAccount(this.context, email)
        GoogleApi.downloadFileFromDrive(fileId,  object : GoogleApi.GoogleApiListener<String> {
            override fun success(data: String) {
                try {
                    //LogUtils.printI("download success $data")
                    val temp=JSONObject().apply {
                        this.put("code",0)
                        this.put("fileContent",data)
                        this.put("fileId",fileId)
                    }.toString()
                    result.success(temp)
                }catch (e:Exception){
                    e.printStackTrace()
                }
            }
            override fun error(e: Exception) {
                try {
                    LogUtils.printException("download fair ",e)
                    handleErrorResp(e.message,result)
                }catch (e:Exception){
                    e.printStackTrace()
                }

            }
        })
    }

    private fun  handleGoogleSignLogin(call: MethodCall, result: Result){
        if (currentActivity==null){
            handleErrorResp("android activity is null",result)
            return
        }
        var open_androidx_register=false
        if (open_androidx_register&&currentActivity is AppCompatActivity){
            //混合开发
            GoogleApi.authorizedLoginAndroidX(currentActivity as  AppCompatActivity,createGoogleApiListener(result))
        }else{
           //FlutterActivity 走这里
            this.flutter_result_call=result
            GoogleApi.authorizedLogin(currentActivity!!)
        }
    }
    var flutter_result_call: Result?=null

    private fun  handleErrorResp(errorMsg:String?,result: Result){
        try {
            val temp=JSONObject().apply {
                this.put("code",-1)
                this.put("error",errorMsg)
            }.toString()
            result.success(temp)
        }catch (e:Exception){
            e.printStackTrace()
        }
    }
    private fun  handleGoogleDriveUpload(call: MethodCall, result: Result){
        val json = JSONObject(call.arguments as String)
        val fileName = json.optString("fileName")
        val fileContent = json.optString("fileContent")
        val email = json.optString("email")
        GoogleApi.initDriveByGoogleAccount(this.context, email)
        val tempFile = File(context.filesDir, fileName)
        tempFile.writeText(fileContent)
        GoogleApi.uploadFileToGoogleDrive(tempFile.absolutePath,
            object : GoogleApi.GoogleApiListener<String> {
                override fun success(r: String) {
                    try {
                       // LogUtils.printI("upload success $r")
                        val temp=JSONObject().apply {
                            this.put("code",0)
                            this.put("fileId",r)
                            this.put("fileName",fileName)
                        }.toString()
                        result.success(temp)
                    }catch (e:Exception){
                        e.printStackTrace()
                    }finally {
                        tempFile.delete()
                    }
                }
                override fun error(e: Exception) {
                    try {
                        LogUtils.printException("upload fair ",e)
                        handleErrorResp(e.message,result)
                    }catch (e:Exception){
                        e.printStackTrace()
                    }finally {
                        tempFile.delete()
                    }
                }
            })
    }


    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        this.activityPluginBinding = binding
        //注册ActivityResult的监听器
        this.activityPluginBinding?.addActivityResultListener(activityResultListener)
        currentActivity = binding.activity
        lifecycle = (binding.lifecycle as HiddenLifecycleReference).lifecycle

    }
    private fun  createGoogleApiListener(result:Result):GoogleApi.GoogleApiListener<GoogleSignInAccount>{
        return  object : GoogleApi.GoogleApiListener<GoogleSignInAccount>{
            override fun success(account: GoogleSignInAccount) {
                try {
                    val temp=JSONObject().apply {
                        this.put("code",0)
                        this.put("email",account.email)
                        this.put("idToken",account.idToken)
                        this.put("isExpired",account.isExpired)
                    }.toString()
                    result.success(temp)
                }catch (e:Exception){
                    e.printStackTrace()
                }
            }

            override fun error(e: Exception) {
                LogUtils.printException("google sign login fair ",e)
                handleErrorResp(e.message,result)
            }
        }
    }

    private var activityResultListener=
        PluginRegistry.ActivityResultListener { requestCode, resultCode, data ->
             if (requestCode==GoogleLogin.request_google_login_sign){
                 if (flutter_result_call!=null){
                     GoogleApi.handleAuthorizedLoginIntent(requestCode,resultCode,data,createGoogleApiListener(flutter_result_call!!))
                 }
                 true
             }else{
                 false
             }

        }

    override fun onDetachedFromActivityForConfigChanges() {

    }

    /**
     * 重建activity后，重新渲染上
     */
    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
                  onAttachedToActivity(binding)
    }

    override fun onDetachedFromActivity() {
             this.activityPluginBinding?.removeActivityResultListener(activityResultListener)
             this.activityPluginBinding=null
             currentActivity=null
             lifecycle=null
    }
}
